package logic

import (
	"context"
	"fmt"
	"strings"

	"googee/service/addrbook/model"
	"googee/service/addrbook/rpc/addrbook"
	"googee/service/addrbook/rpc/internal/svc"

	"github.com/jinzhu/copier"
	"github.com/ppmoon/gbt2260"
	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type CreateAddrBookLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateAddrBookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAddrBookLogic {
	return &CreateAddrBookLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建地址
func (l *CreateAddrBookLogic) CreateAddrBook(in *addrbook.CreateAddrRequest) (*addrbook.AddrBookInfo, error) {
	resp := &addrbook.AddrBookInfo{}

	m := &model.Addrbook{
		UserId:    in.UserId,
		AdCode:    in.AdCode,
		Phone:     in.Phone,
		Street:    in.Street,
		IsDefault: in.IsDefault,
	}

	region := gbt2260.NewGBT2260()
	adcodes := region.SearchGBT2260(fmt.Sprintf("%v", in.AdCode))
	m.Area = strings.Join(adcodes, "")

	result, err := l.svcCtx.AddrbookModel.Insert(l.ctx, m)
	if err != nil {
		return nil, status.Error(codes.Unknown, "insert failed")
	}

	lastId, err := result.LastInsertId()
	if err != nil {
		return nil, status.Error(codes.Unknown, "insert failed")
	}

	m.Id = lastId

	copier.Copy(&resp, m)
	return resp, nil
}
